package com.sx.pipeline.ui.task

import android.app.Application
import android.net.Uri
import android.text.TextUtils
import com.alibaba.android.arouter.launcher.ARouter
import com.amap.api.services.core.PoiItem
import com.blankj.utilcode.util.ToastUtils
import com.sx.mvvmlibs.base.BaseViewModel
import com.sx.mvvmlibs.bus.RxBus
import com.sx.mvvmlibs.event.SingleLiveEvent
import com.sx.mvvmlibs.http.CommonObserver
import com.sx.mvvmlibs.utils.Logs
import com.sx.mvvmlibs.utils.RxThreadHelper
import com.sx.pipeline.R
import com.sx.pipeline.app.config.ReleaseNeedsType
import com.sx.pipeline.app.config.ReleaseTaskType
import com.sx.pipeline.app.event.BusEvent
import com.sx.pipeline.app.event.EventTypes
import com.sx.pipeline.app.event.RefreshEvent
import com.sx.pipeline.app.model.CYBaseViewModel
import com.sx.pipeline.arouth.RouteManager
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.repos.http.req.*
import com.sx.pipeline.repos.http.res.*
import com.sx.pipeline.ui.task.entity.ReleaseTaskListVO
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.rong.imkit.RongIM

/**
 * @Author: YY
 * @Date: 2022/4/13
 * @Description: TODO
 */
class ReleaseTaskVM(app: Application) : CYBaseViewModel(app) {
    /**
     * 获取我发布的任务类型标题
     */
    fun getReleaseTabsList(): List<String> {
        val tabs = mutableListOf<String>()
        tabs.add(getApplication<Application>().getString(R.string.txt_pending_review))
        tabs.add(getApplication<Application>().getString(R.string.txt_upcoming))
        tabs.add(getApplication<Application>().getString(R.string.txt_in_progress))
        tabs.add(getApplication<Application>().getString(R.string.txt_completed))
        tabs.add(getApplication<Application>().getString(R.string.txt_over))
        tabs.add(getApplication<Application>().getString(R.string.txt_rejected))
        tabs.add(getApplication<Application>().getString(R.string.txt_cancelled))
        return tabs
    }

    fun getReleaseTaskTabsIdList(): List<Int> {
        val tabs = mutableListOf<Int>()
        tabs.add(ReleaseTaskType.PENDING_REVIEW.code)
        tabs.add(ReleaseTaskType.AGENCY.code)
        tabs.add(ReleaseTaskType.IN_PROGRESS.code)
        tabs.add(ReleaseTaskType.COMPLETED.code)
        tabs.add(ReleaseTaskType.OVER.code)
        tabs.add(ReleaseTaskType.REJECTED.code)
        tabs.add(ReleaseTaskType.CANCELLED.code)
        return tabs
    }
    /**
     * 获取任务配置数据
     */
    val taskListEvent: SingleLiveEvent<TaskConfigVo> = SingleLiveEvent()

    //任务标题
    val taskTitleData: MutableList<String> = ArrayList()

    //计量单位
    val taskUnitData: MutableList<String> = ArrayList()

    //任务性质
    val taskNatureData: MutableList<String> = ArrayList()

    //任务类型
    val taskTypeData: MutableList<String> = ArrayList()

    //任务现场情况
    val taskConditionData: MutableList<String> = ArrayList()
    fun getTask() {
        addSubscribe(
            mModel.getTask()
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<TaskConfigVo, BaseViewModel<*>>
                    (this, true) {

                    override fun onResult(result: TaskConfigVo) {
                        taskListEvent.postValue(result)
                        for (data in result.TITLE) {
                            taskTitleData?.add(data.name)
                        }
                        for (data in result.UNIT_OF_MEASUREMENT) {
                            taskUnitData?.add(data.name)
                        }
                        for (data in result.NATURE) {
                            taskNatureData?.add(data.name)
                        }
                        for (data in result.TASK_TYPE) {
                            taskTypeData?.add(data.name)
                        }
                        for (data in result.LIVE_SITUATION) {
                            taskConditionData?.add(data.name)
                        }
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort("$msg")

                    }
                })
        )
    }


    /**
     * 发布任务
     */
    val auditGroupSuccessEvent: SingleLiveEvent<TaskGroupVO> = SingleLiveEvent()
    fun getTaskAdd(
        title: String,//任务标题
        taskDescription: String, //任务描述
        name: String, //项目名称
        workload: String, //工作量
        unit: String, //计量单位
        longitude: String, //经度
        latitude: String, //纬度
        addressDetail: String, //详细地址
        nature: String, //任务性质
        startTime: String, //开始日期
        endTime: String, //结束日期
        contact: String, //联系人
        contactPhone: String, //联系电话
        taskType: String, //任务类型
        taskCondition: String, //任务现场情况
        livePictures: String, //现场图片
        constructionDrawing: String, //施工图纸
        formalities: String, //审批手续
    ) {
        val dto = TaskAddDTO(
            title,
            taskDescription,
            name,
            workload,
            unit,
            longitude,
            latitude,
            addressDetail,
            nature,
            startTime,
            endTime,
            contact,
            contactPhone,
            taskType,
            taskCondition,
            livePictures,
            constructionDrawing,
            formalities
        )
        if (TextUtils.isEmpty(title)) {
            ToastUtils.showShort("请选择任务标题")
            return
        }
//        if (TextUtils.isEmpty(taskDescription)) {
//            ToastUtils.showShort("请输入任务描述")
//            return
//        }
        if (TextUtils.isEmpty(name)) {
            ToastUtils.showShort("请输入项目名称")
            return
        }
//        if (TextUtils.isEmpty(workload)) {
//            ToastUtils.showShort("请输入工作量")
//            return
//        }
//        if (TextUtils.isEmpty(unit)) {
//            ToastUtils.showShort("请选择计量单位")
//            return
//        }
        if (TextUtils.isEmpty(addressDetail) && TextUtils.isEmpty(longitude) && TextUtils.isEmpty(
                latitude
            )
        ) {
            ToastUtils.showShort("请选择施工地点")
            return
        }
        if (TextUtils.isEmpty(nature)) {
            ToastUtils.showShort("请选择任务性质")
            return
        }
        if (TextUtils.isEmpty(startTime)) {
            ToastUtils.showShort("请选择开始时间")
            return
        }
        if (TextUtils.isEmpty(endTime)) {
            ToastUtils.showShort("请选择结束时间")
            return
        }
        if (TextUtils.isEmpty(contact)) {
            ToastUtils.showShort("请选择现场负责人")
            return
        }
        if (TextUtils.isEmpty(contactPhone)) {
            ToastUtils.showShort("请输入现场负责人电话")
            return
        }
        if (TextUtils.isEmpty(taskType)) {
            ToastUtils.showShort("请选择任务类型")
            return
        }
        if (TextUtils.isEmpty(taskCondition)) {
            ToastUtils.showShort("请选择任务现场勘探情况")
            return
        }
        showLoadingDialog()
        addSubscribe(
            mModel.getTaskAdd(dto)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<TaskGroupVO, BaseViewModel<*>>
                    (this, true) {

                    override fun onResult(result: TaskGroupVO) {
                        dismissLoadingDialog()
                        ToastUtils.showShort("任务发布完成")
                        auditGroupSuccessEvent.postValue(result)
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        dismissLoadingDialog()
                        ToastUtils.showShort("$msg")

                    }
                })
        )
    }

    //地图页面拿到的位置数据
    val locationEvent: SingleLiveEvent<PoiItem> = SingleLiveEvent()
    override fun registerRxBus() {
        addSubscribe(
            RxBus.getDefault().toObservable(BusEvent::class.java)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    when (it.type) {
                        EventTypes.SELECT_SITE.code -> {
                            val poiItem: PoiItem = it.data as PoiItem
                            locationEvent.postValue(poiItem)
                            Logs.d("选择的地点：${poiItem.provinceName} === ${poiItem.cityName} === ${poiItem.adName}===${poiItem.title}===${poiItem.snippet} ")
                            Logs.d("选择的地点：${poiItem.latLonPoint.latitude} === ${poiItem.latLonPoint.longitude}")
                        }
                    }
                }
        )
    }


    /**
     * 获取任务发布列表
     */
    var page=1
    val releaseTaskListEvent: SingleLiveEvent<List<ReleaseTaskVo>> = SingleLiveEvent()
    fun putTaskList(status: Int) {
        addSubscribe(
            mModel.putTaskList(status,page)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Ipage<ReleaseTaskVo>, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: Ipage<ReleaseTaskVo>) {
                        releaseTaskListEvent.postValue(result.records)
                        dismissLoadingDialog()
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        dismissLoadingDialog()
                        ToastUtils.showShort(msg)
                    }
                })
        )
    }


    /**
     * 取消任务
     */
    val successTaskEvent: SingleLiveEvent<Boolean> = SingleLiveEvent()
    fun getCancelTask(id: Int) {
        addSubscribe(
            mModel.getCancelTask(id)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Any, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: Any) {
                        ToastUtils.showShort("取消成功")
                        successTaskEvent.postValue(true)
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                    }
                })
        )
    }

    /**
     * 结束任务
     */
    fun getEndTask(id: Int) {
        addSubscribe(
            mModel.getEndTask(id)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Any, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: Any) {
                        ToastUtils.showShort("任务结束成功")
                        successTaskEvent.postValue(true)
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                    }
                })
        )
    }

    /**
     * 删除任务
     */
    fun getRemoveTask(id: Int) {
        addSubscribe(
            mModel.getRemoveTask(id)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Any, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: Any) {
                        ToastUtils.showShort("任务删除成功")
                        successTaskEvent.postValue(true)
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                    }
                })
        )
    }


    /**
     * 任务详情
     */
    var taskDetailDataEvent: SingleLiveEvent<TaskDetailVo> = SingleLiveEvent()
    fun getTaskDetail(id: Int) {
        addSubscribe(
            mModel.getTaskDetail(id)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<TaskDetailVo, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: TaskDetailVo) {
                        taskDetailDataEvent.postValue(result)
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                    }
                })
        )
    }

    /**
     * 申请延期
     */
    val successTaskDelayEvent: SingleLiveEvent<Boolean> = SingleLiveEvent()
    fun getTaskDelay(id: Int,delayTime:String,delayReason:String) {
        if (TextUtils.isEmpty(delayTime)){
            ToastUtils.showShort("请选择延期时间")
            return
        }
        if (TextUtils.isEmpty(delayReason)){
            ToastUtils.showShort("请填写延期原因")
            return
        }
        var dto=TaskDelayDTO(id,delayTime,delayReason)
        addSubscribe(
            mModel.getTaskDelay(dto)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Any, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: Any) {
                        successTaskDelayEvent.postValue(true)
                        ToastUtils.showShort("任务延期申请成功")
                        finish()
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                    }
                })

        )
    }


    /**
     * 任务评价
     */
    val addTaskEvaluateEvent: SingleLiveEvent<Boolean> = SingleLiveEvent()
    fun addTaskEvaluate(dto:List<TaskEvaluateDTO>) {
        addSubscribe(
            mModel.addTaskEvaluate(dto)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Any, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: Any) {
                        addTaskEvaluateEvent.postValue(true)
                        //通知列表刷新
                        RxBus.getDefault().post(RefreshEvent())
                        ToastUtils.showShort("提交成功")
                        finish()
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                    }
                })
        )
    }


    /**
     * 评价列表
     */
    val taskEvaluateListEvent: SingleLiveEvent<List<TaskEvaluateVO>> = SingleLiveEvent()
    fun getEvaluate(orderId: Int) {
        addSubscribe(
            mModel.getEvaluate(orderId)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<List<TaskEvaluateVO>, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: List<TaskEvaluateVO>) {
                        taskEvaluateListEvent.postValue(result)
                        dismissLoadingDialog()
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        dismissLoadingDialog()
                        ToastUtils.showShort(msg)
                    }
                })
        )
    }

    /**
     * 创建群聊
     */
    val groupSuccessEvent: SingleLiveEvent<Boolean> = SingleLiveEvent()
    fun getTaskCreateGroup(type: Int, name: String,orderId: String) {
        val dto = TaskCreateGroupDTO(type, name,orderId)
        addSubscribe(
            mModel.getTaskCreateGroup(dto)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Any, BaseViewModel<*>>
                    (this, false) {
                    override fun onResult(result: Any) {
                        groupSuccessEvent.postValue(true)
                        ToastUtils.showShort("群聊创建成功")
                        dismissLoadingDialog()
                        getRongGroupListOne{
                            ARouter.getInstance().build(RoutePath.Chat.CHAT_GROUP).navigation()
                        }
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                        dismissLoadingDialog()
                    }
                })
        )
    }

    fun getRongGroupListOne(refreshSuccess:(()->Unit)) {
        addSubscribe(
            mModel.getRongGroupList()
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<List<RongGroupVO>, BaseViewModel<*>>
                    (this, false) {
                    override fun onResult(result: List<RongGroupVO>) {

                        refreshRongGroupInfo(result,refreshSuccess)
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                        dismissLoadingDialog()
                    }
                })
        )

    }

    private fun refreshRongGroupInfo(friendList: List<RongGroupVO>,refreshSuccess:(()->Unit)) {
        //融云IM -> 刷新群组信息
        for (i in friendList.indices) {
            //后台拿到的联系人列表id 比对 融云id相同则缓存
            val group = io.rong.imlib.model.Group(
                friendList[i].id,
                friendList[i].name,
                Uri.parse("")
            )
            //通过网络请求动态加载群信息
            RongIM.getInstance().refreshGroupInfoCache(group)
            Logs.d("re缓存群聊信息成功：" + group)
        }
        refreshSuccess.invoke()
    }

}